package com.yoso.file.sdk.upload;

import cn.hutool.core.date.StopWatch;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import com.yoso.core.dto.ResponseResult;
import com.yoso.file.sdk.response.UploadResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

@Slf4j
public class LocalHostUpload extends AbstractUploadFile {

    @Value("${file.upload-path:default}")
    private String uploadPath;

    /**
     * 上传多个文件
     *
     * @param multipartFile
     * @return {@link ResponseResult }<{@link List }<{@link UploadResponse }>>
     * @author shizejin
     * @date 2024/12/24
     */
    @Override
    public UploadResponse upload(MultipartFile multipartFile) {
        StopWatch stopWatch = new StopWatch();
//           上传的文件名
        final String filename = multipartFile.getOriginalFilename();
//            TODO:对/优化
        String filePath = parseFilePath(filename);
//           文件大小
        long size = multipartFile.getSize();
        stopWatch.start();
        log.info("===>>>>>上传文件:{}", filename);
        log.info("===>>>>>文件路径：{}", filePath);
        log.info("===>>>>>文件大小：{}字节", size);
        InputStream inputStream = null;
        try {
            inputStream = multipartFile.getInputStream();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        FileUtil.writeFromStream(inputStream, FileUtil.newFile(filePath), true);
        stopWatch.stop();
        log.info("===>>>>>上传结束，耗时：{}", stopWatch.getLastTaskTimeMillis());
        log.info("----------------------------");

        UploadResponse uploadResponse = new UploadResponse();
        uploadResponse.setFileId(generateFileId());
        uploadResponse.setFilePath(filePath);
        uploadResponse.setFileName(filename);
        return uploadResponse;
    }

    private String parseFilePath(String fileName) {
        String rootPath = uploadPath;
        if (StrUtil.isBlank(uploadPath) || StrUtil.equals(uploadPath, "default")) {
            rootPath = System.getProperty("java.io.tmpdir") + "file-sdk";
        }
        return rootPath + generateRandomPath() + File.separator + fileName;
    }
}
